<template>
    <div>
        <el-upload ref="upL" :action="action" :http-request="uploadSectionFile" :on-preview="handlePreview"
                   :on-remove="handleRemove"
                   :list-type="listType"
                   :accept="!typeImg?'':'.jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP'"
                   :file-list="fileList" :before-upload="handleBefore" multiple :limit="isLimit">
            <el-button type="primary" v-if="!typeImg"  plain>{{ btnName }}</el-button>
            <!--<img src="../../assets/img/datu.png.png" v-if="typeImg"/>-->
            <i v-preview="isPreview" v-if="typeImg" class="el-icon-plus"></i>
            <div slot="tip"></div>
        </el-upload>
        <el-progress v-show="showProgress" :status="upStatus" :percentage="uploadPercent"></el-progress>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
<script>
    import { getCookie, Token } from '@/utils/cookie'
    import { uploadFileMulti, uploadFileSingle, preview } from "@/api/attachment/attachment";

    export default {
        model: {
            prop: 'attachments',
            event: 'upload'
        },
        props: {
            attachments: {
                type: Array,
                default: () => []
            },
            // typeImg:{
            //
            // },
            btnName: {
                default: '上传附件'
            },
            listType: {
                type: String,
                default: 'text'
            },
            isPreview: {
                type: Boolean,
                default: false,
            },
            isGoStop: {
                type: Boolean,
                default: false,
            },
            isLimit: {
                default: 100,
            }

        },
        directives: {
            preview: {
                inserted(el, binding) {
                    console.log(binding)
                    console.log(el)
                    if (binding.value) {
                        el.parentNode.style.display = 'none'
                        let className = document.getElementsByClassName('el-upload-list__item-delete')
                        for (let i = 0; i < className.length; i++) {
                            const cn = className[i]
                            cn.style.display = 'none'
                        }
                    }
                },
                update(el, binding) {
                    console.log(binding)
                },
            }
        },
        data() {
            return {
                action: '/attachments/uploadMulti',
                headers: {
                    'Authorization': getCookie(Token),
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                uploadPercent: 0,
                upStatus: '',
                dialogImageUrl: '',
                showProgress: false,
                dialogVisible: false,
            }
        },
        mounted() {
            if (this.typeImg && this.attachments && this.attachments.length > 0) {
                this.getUrl(0)
            }
        },
        methods: {
            // cleanFiles() {
            //     this.attachments.splice(0, this.attachments.length)
            // },
            // 覆盖element组件自带上传事件
            uploadSectionFile(param) {
                let fileObj = param.file;

                console.log(fileObj)
                // FormData 对象
                let form = new FormData();
                // 文件对象
                form.append("file", fileObj);
                uploadFileSingle(form).then(res => {
                    if (!this.attachments) {
                        this.attachments = []
                    }
                    this.attachments.push(res.data)
                    this.$emit('upload', this.attachments)
                    this.uploadPercent = 100
                    this.showProgress = false
                    if (this.typeImg) {
                        this.getBase(this.attachments.length - 1)
                    }
                })

                // 原生上传
                // 接收上传文件的后台地址
                // let FileController = "/api/attachments/uploadSigle";
                // var xhr = new XMLHttpRequest();
                // xhr.open("post", FileController, true);
                // xhr.setRequestHeader('Authorization', getCookie(Token))
                // this.$store.commit('SET_LOADING_STATUS', true)
                // console.log(this.$store.getters.loadingBtn)
                // // xhr.upload.addEventListener("progress", this.progressFunction, false); //监听上传进度
                // xhr.onload = () => {
                //     let res = JSON.parse(xhr.response)
                //     console.log(res)
                //     this.$store.commit('SET_LOADING_STATUS', false)
                //     console.log(this.$store.getters.loadingBtn)
                //     this.attachments.push(res.data)
                //     this.$emit('upload', this.attachments)
                //     this.uploadPercent = 100
                //     this.showProgress = false
                // };
                // xhr.send(form);
            },
            progressFunction() {
                this.showProgress = true
            },
            handleBefore(file) {
                if(this.isGoStop){
                    return false;
                }
                console.log(file)
            },
            handleRemove(file, fileList) {
                console.log(file)
                this.attachments = this.attachments.filter(attachment => attachment.id !== file.id)
                this.$emit('upload', this.attachments)
            },
            handlePreview(file) {
                if (this.typeImg) {
                    this.dialogImageUrl = file.url;
                    this.dialogVisible = true;
                }
            },
            getUrl(num) {
                if (num < this.attachments.length) {
                    preview(this.attachments[num].id).then(res => {
                        let url = res.data
                        let strUrl = res.data.substr(0, url.length - 2)
                        this.attachments[num].viewPath = strUrl.substr(url.indexOf('=') + 1, strUrl.length)
                        this.getUrl(num + 1)
                    }).catch(err =>{
                        this.attachments[num].viewPath = 'http://img10.360buyimg.com/n1/jfs/t17479/331/463860348/54829/98c31e6d/5a7bb620N7ca92f1c.jpg'
                        this.getUrl(num + 1)
                    })
                }
            },
            getBase(length) {
                preview(this.attachments[length].id).then(res => {
                    let url = res.data
                    let strUrl = res.data.substr(0, url.length - 2)
                    this.attachments[length].viewPath = strUrl.substr(url.indexOf('=') + 1, strUrl.length)
                })
            }
        },
        watch: {},
        computed: {
            fileList() {
                let fileList = []
                if (this.attachments && this.attachments.length > 0) {
                    this.attachments.forEach((attachment) => {
                        if (attachment.fileName.length > 20) {
                            attachment.fileName = attachment.fileName.substr(0, 20) + '...'
                        }
                        fileList.push({
                            name: attachment.fileName,
                            url: attachment.viewPath,
                            id: attachment.id
                        })
                    })
                }
                return fileList
            },
            typeImg() {
                return this.listType !== 'text'
            }
        },
    }
</script>
